<template>
  <!-- 多选下拉框组件 -->
  <view class="multi-picker">
    <!-- 触发用输入框 -->
    <view class="text_box" :style="'height:' + height">
      <view
        v-if="localSelected.length <= 0"
        class="placeholder"
        :style="'font-size:' + fontSize"
        >{{ placeholder }}</view
      >
      <view class="tag_box" v-else>
        <view
          class="tag_item"
          v-for="item in localSelected"
          :key="item[idName]"
        >
          <text class="tag_text">{{ item[keyName] }}</text>
        </view>
      </view>
      <u-icon
        v-if="showIcon"
        :size="iconSize"
        slot="right"
        name="arrow-right"
        @click="showFn"
      ></u-icon>
    </view>

    <!-- 弹出选择层 -->
    <u-popup
      :show="show"
      mode="bottom"
      round="16"
      @close="closePopup"
      :closeOnClickOverlay="true"
      height="500px"
    >
      <view class="popup-content">
        <!-- 头部操作栏 -->
        <view class="popup-header">
          <text class="btn-cancel" @click="cancel">取消</text>
          <text class="title">{{ title }}</text>
          <text class="btn-confirm" @click="confirm">确定</text>
        </view>

        <u-search
          v-if="showSearch"
          placeholder="请输入搜索内容"
          hape="round"
          v-model="searchText"
          :clearabled="true"
          :showAction="false"
        ></u-search>

        <!-- 选项容器（带滚动） -->
        <scroll-view scroll-y="true" class="options-container">
          <!-- 选项按钮（支持多选） -->
          <view class="sc_box">
            <view
              class="btn_box"
              v-for="item in filteredList"
              :key="item[idName]"
            >
              <view
                class="option-item"
                :class="isSelected(item) ? 'option-selected' : 'option-default'"
                @click="toggleSelect(item)"
              >
                <text class="option-text">{{ item[keyName] }}</text>
              </view>
            </view>
            <view class="btn_box" @click="addCustomTag">
              <view class="option-item add_item">
                <u-icon name="plus" size="14" color="#9EA5B2"></u-icon>
                <text class="option-text">自定义</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <u-popup :show="showAddTag" :round="10" safeAreaInsetBottom>
      <view class="popup-content">
        <!-- 头部操作栏 -->
        <view class="popup-header">
          <text class="btn-cancel" @click="closeAdd">取消</text>
          <text class="title">添加标签</text>
          <text class="btn-confirm" @click="confirmAddtag">确定</text>
        </view>
      </view>
      <view class="form" style="height: 50vh;">
        <u--form
          labelPosition="left"
          :model="form"
          ref="addForm"
          labelWidth="150rpx"
          :labelStyle="labelStyle"
        >
          <u-form-item label="标签名称" prop="style" borderBottom>
            <u--input
              placeholder="请输入标签名称"
              v-model="form.tag"
              border="none"
              :fontSize="fontSize"
            ></u--input>
          </u-form-item>
          <u-form-item label="标签级别" prop="style" borderBottom>
            <u-radio-group
              v-model="form.customerResourceTagLevel"
              placement="row"
              activeColor="#a22d27"
            >
              <u-radio
                :customStyle="{ marginRight: '8px' }"
                v-for="(item, index) in levelList"
                :key="index"
                :label="item.label"
                :name="item.value"
              >
              </u-radio>
            </u-radio-group>
          </u-form-item>
        </u--form>
      </view>
    </u-popup>
  </view>
</template>
  
  <script>
export default {
  name: "TagPicker",
  /**
   * 组件模型配置，支持v-model双向绑定
   */
  model: {
    prop: "value", // 绑定的属性名
    event: "input", // 触发的事件名
  },
  props: {
    /**
     * 已选中的值（数组格式）
     * @vModel
     */
    value: {
      type: Array,
      default: () => [],
    },
    /**
     * 选项数据源
     * @required
     */
    list: {
      type: Array,
      required: true,
    },
    /**
     * 控制弹出层显示
     */
    show: {
      type: Boolean,
      default: false,
    },
    /**
     * 弹出层标题
     */
    title: {
      type: String,
      default: "请选择",
    },
    /**
     * 是否显示搜索框
     */
    showSearch: {
      type: Boolean,
      default: false,
    },
    /**
     * 显示文本的字段名
     */
    keyName: {
      type: String,
      default: "name",
    },
    /**
     * 唯一标识字段名
     */
    idName: {
      type: String,
      default: "id",
    },
    /**
     * 输入框占位符
     */
    placeholder: {
      type: String,
      default: "请选择",
    },
    /**
     * 输入框文字对齐方式
     * 可选值：left/center/right
     * 默认："left"
     */
    inputAlign: {
      type: String,
      default: "left",
    },
    /**
     * 输入框字体大小
     * 默认："15px"
     */
    fontSize: {
      type: String,
      default: "15px",
    },
    /**
     * 下拉图标大小
     * 默认："15px"
     */
    iconSize: {
      type: String,
      default: "15px",
    },
    /**
     * 是否显示下拉箭头图标
     * 默认：true
     */
    showIcon: {
      type: Boolean,
      default: true,
    },
    height: {
      type: String,
      default: "70rpx",
    },
  },
  data() {
    return {
      // innerShow: this.show, // 内部弹窗显示状态
      searchText: "", // 搜索关键词
      localSelected: [...this.value], // 临时选择的值
      tempSelected: [...this.value], // 临时选择的值
      showAddTag: false,
      form: {
        tag: "",
        customerResourceTagLevel: "",
      },

      labelStyle: {
        "font-size": "24rpx",
      },
      levelList: [
        {
          label: "记录",
          value: "Record",
        },
        {
          label: "普通",
          value: "Info",
        },
        {
          label: "优质",
          value: "Excellent",
        },
      ],
    };
  },
  watch: {
    /**
     * 监听外部value变化更新本地选中值
     */
    value: {
      immediate: true,
      handler(newVal) {
        // 同步更新本地值和临时值
        this.localSelected = [...newVal];
        this.tempSelected = [...newVal];
      },
    },
  },
  computed: {
    /**
     * 过滤后的选项列表（带搜索功能）
     */
    filteredList() {
      if (!this.searchText) return this.list;
      return this.list.filter((item) =>
        item[this.keyName].includes(this.searchText)
      );
    },
    /**
     * 输入框显示文本（逗号分隔的选中项）
     */
    displayText() {
      return this.localSelected.map((item) => item[this.keyName]).join(", ");
    },
  },
  methods: {
    /**
     * 添加标签
     */
    confirmAddtag() {
      if (this.form.tag == "") {
        uni.showToast({
          title: "请输入标签名称",
          icon: "none",
        });
        return;
      }
      if (this.form.customerResourceTagLevel == "") {
        uni.showToast({
          title: "请选择标签级别",
          icon: "none",
        });
        return;
      }
      console.log(this.form);

      this.$emit("addTag", this.form,this.tempSelected);
      this.closeAdd();
    },
    /**
     * 关闭
     */
    closeAdd() {
      this.$nextTick(() => {
        this.form = {
          tag: "",
          customerResourceTagLevel: "",
        };
        this.showAddTag = false;
      });
    },
    /**
     * 添加自定义标签
     */
    addCustomTag() {
      this.showAddTag = true;
    },
    /**
     * 关闭弹出层
     */
    closePopup() {
      // this.innerShow = false;
      this.tempSelected = [...this.localSelected];
      this.$emit("update:show", false);
      this.$emit("close");
    },
    /**
     * 取消选择（恢复原始值）
     */
    cancel() {
      this.tempSelected = [...this.localSelected]; // 重置为已确认的值
      this.closePopup();
    },
    /**
     * 确认选择
     * @emits input 更新v-model值
     * @emits confirm 确认事件
     */
    confirm() {
      console.log(this.tempSelected);

      this.localSelected = [...this.tempSelected];
      console.log(this.localSelected);

      this.$emit("input", this.localSelected);
      this.$emit("confirm", this.localSelected);
      this.closePopup();
    },
    /**
     * 判断是否选中
     * @param {Object} item 当前选项
     * @returns {Boolean} 是否选中
     */
    isSelected(item) {
      return this.tempSelected.some(
        (selected) => selected[this.idName] === item[this.idName]
      );
    },
    /**
     * 切换选中状态
     * @param {Object} item 切换的选项
     */
    toggleSelect(item) {
      const index = this.tempSelected.findIndex(
        (selected) => selected[this.idName] === item[this.idName]
      );
      if (index > -1) {
        this.tempSelected.splice(index, 1);
      } else {
        this.tempSelected.push(item);
      }
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.text_box {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.popup-content {
  padding: 32rpx;
  // max-height: 70vh; // 限制最大高度

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 24rpx;

    .title {
      font-weight: bold;
      font-size: 34rpx;
    }

    .btn-cancel {
      color: #9ea5b2;
      font-size: 24rpx;
      padding: 16rpx 32rpx;
    }
    // 操作按钮样式

    .btn-confirm {
      color: #a22c26;
      font-size: 24rpx;
      padding: 16rpx 32rpx;
    }
  }

  // 搜索框样式
  .search-input {
    margin-bottom: 24rpx;
    background: #f5f5f5;
    border-radius: 16rpx;
    padding: 16rpx 24rpx;
  }

  // 选项容器样式
  .options-container {
    height: 50vh; // 限制可滚动区域高度
    margin-top: 18rpx;
    .sc_box {
      display: flex;
      //   justify-content: space-around;
      flex-wrap: wrap;
    }
    .btn_box {
      margin: 16rpx 5rpx 0rpx;
    }
    .option-item {
      padding: 5rpx 20rpx;
      border: 2rpx solid #ddd;
      border-radius: 8rpx;
      background-color: #fff;
      transition: all 0.2s ease;

      &-text {
        font-size: 22rpx;
        color: #333;
      }

      // 选中状态样式
      &.option-selected {
        border-color: #a22c26;
        background-color: #fbe6e8;

        .option-text {
          color: #a22c26;
          font-weight: 500;
        }
      }
      &.option-default {
        border-color: #a22c26;
        .option-text {
          color: #a22c26;
          font-weight: 500;
        }
      }
      &.add_item {
        border-color: #9ea5b2;
        display: flex;
        .option-text {
          display: inline-block;
          margin-left: 5rpx;
          color: #9ea5b2;
          font-weight: 500;
        }
      }

      // 点击反馈效果
      &:active {
        transform: scale(0.98);
      }
    }
  }
}
.tag_box {
  display: flex;
  flex-wrap: wrap;
  .tag_item {
    margin: 5rpx 8rpx;
  }
  .tag_text {
    font-size: 22rpx;
    padding: 2rpx 20rpx;
    background-color: #fbe6e8;
    color: #a22c26;
    border: 1rpx solid #a22c26;
    border-radius: 8rpx;
    overflow: hidden;
  }
}
.placeholder {
  color: #999;
  font-size: 15px;
  padding-left: 10rpx;
}
.form {
  padding: 40rpx;
  box-sizing: border-box;
}
</style>
  